package com.example.tourism.utils.API;

import okhttp3.*;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ERNIE_Bot_4 {
    private final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
            .readTimeout(115, TimeUnit.SECONDS)    // 设置读取超时时间为115秒
            .build();

    private String API_KEY;
    private String SECRET_KEY;
    private String bodyValue;  //传入的值
    public ERNIE_Bot_4(String API_KEY, String SECRET_KEY, String bodyValue){
        this.API_KEY = API_KEY;
        this.SECRET_KEY = SECRET_KEY;
        this.bodyValue =bodyValue;
    }
    public String getResponse() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        okhttp3.RequestBody body = RequestBody.create(mediaType, bodyValue);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        okhttp3.RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
